/**
 * Created by wzq on 15-3-28.
 */

var express = require('express');
var router = express.Router();
var debug = require('debug')('auth');
var WeixinApi = require("../weixin/WeixinApi.js");
var weixinObj = new WeixinApi();
var url = require('url');


// code=CODE&state=STATE
router.get('/', function(req, res, next) {

	var query = url.parse(req.url, true).query;
	var code = query.code;
	if (!code) {
		res.redirect('/auth/forbidden');
		return;
	}

	debug('auth with code=', query.code);

	// get userid
	weixinObj.getUseridByCode(code).then(function(data) {
		debug('auth, userId=', data);
		req.session.userId = data;
		res.redirect('/home');
	}, function(err) {
		res.redirect('/auth/forbidden');
	});
});


router.get('/forbidden', function(req, res, next) {
	res.status(405).end('forbidden');
});

module.exports = exports = router;